package com.woniuxy.project.campus.canteen.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniuxy.project.campus.canteen.dto.QueryProductAllDto;
import com.woniuxy.project.campus.canteen.mapper.ProductTypeMapper;
import com.woniuxy.project.campus.canteen.mapper.ShopsMapper;
import com.woniuxy.project.campus.canteen.model.ModifyDiscountParam;
import com.woniuxy.project.campus.canteen.model.ProductList;
import com.woniuxy.project.campus.canteen.mapper.ProductListMapper;
import com.woniuxy.project.campus.canteen.model.ProductType;
import com.woniuxy.project.campus.canteen.model.Shops;
import com.woniuxy.project.campus.canteen.param.AddProductParam;
import com.woniuxy.project.campus.canteen.param.ModifyPriceParam;
import com.woniuxy.project.campus.canteen.param.ModifyStatusParam;
import com.woniuxy.project.campus.canteen.param.ModifyTypeParam;
import com.woniuxy.project.campus.canteen.service.ProductListService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.project.campus.canteen.util.AliyunOSS;
import com.woniuxy.project.campus.canteenModelform.SelectProShopInfo;
import com.woniuxy.project.campus.util.StaticData;
import com.woniuxy.project.campus.util.TokenTool;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 猫将军
 * @since 2025年02月17日
 */
@Service
public class ProductListServiceImpl extends ServiceImpl<ProductListMapper, ProductList> implements ProductListService {
    private final Lock lock = new ReentrantLock();
    @Resource
    private ShopsMapper shopsMapper;
    @Resource
    private ProductListMapper productListMapper;
    @Resource
    private ProductTypeMapper productTypeMapper;
    @Resource
    private AliyunOSS aliyunOSS;


    @Override
    @Transactional
    public void addProduct(AddProductParam bean) throws IOException {
        Integer id = TokenTool.getUserIdByToken(bean.getToken());
        QueryWrapper<Shops> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account_id",id);
        Shops shops = shopsMapper.selectOne(queryWrapper);
        if (shops== null){
            throw new RuntimeException("未找到您的店铺信息");
        }
        ProductList product1 = new ProductList();
        QueryWrapper<ProductList> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("product_name",bean.getProductName());
        ProductList productList = productListMapper.selectOne(queryWrapper1);
        if (productList!=null){
            throw new RuntimeException("该菜品名已存在");
        }
        queryWrapper1.clear();

        //价格不能小于0
        if (bean.getProductPrice().compareTo(BigDecimal.ZERO)<0){
            throw new RuntimeException("价格不能小于0");
        }
        //对商品折扣价进行参数校验
        if (bean.getDiscountPrice()!=null){
            BigDecimal discountPrice = bean.getDiscountPrice();
            if ( discountPrice.compareTo(BigDecimal.ONE) >= 0) {
                throw new RuntimeException("折扣大于等于1");
            }
        }
        //查询所有商品类型
        QueryWrapper<ProductType> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("id", bean.getProductTypeId());
        ProductType productType = productTypeMapper.selectOne(queryWrapper2);
        if (productType==null){
            throw new RuntimeException("未找到该商品类型");
        }
        //上传商品图片
        InputStream inputStream = bean.getFile().getInputStream();
        byte[] bytes = new byte[1024];
        inputStream.read(bytes);
        //判断文件类型
        if (!(aliyunOSS.isJpg(bytes)||aliyunOSS.isPng(bytes))) {
            throw new IOException("文件类型不正确");
        }
        //获取文件后缀名
        String filenameExtension = StringUtils.getFilenameExtension( bean.getFile().getOriginalFilename());
        //获取前缀
        String str = UUID.randomUUID().toString();
        //上传到阿里云oss
        String url = aliyunOSS.uploadFile(bean.getFile().getInputStream(), str + "." + filenameExtension, "womengjiwojuan");
        //添加菜品
        product1.setProductName(bean.getProductName());
        //商品描述
        product1.setRemark(bean.getProductDescription());
        //商品价格
        product1.setPrice(bean.getProductPrice());
        //创建时间
        product1.setCreationTime(LocalDateTime.now());
        //商品图片url
        product1.setPicture(url);

        if(bean.getDiscountPrice().compareTo(BigDecimal.ZERO)==0){
            product1.setDiscountPrice(null);
        }
        //折扣

        //所属店铺id
        product1.setShopId(shops.getId());
        //菜品状态
        product1.setProductStatus(StaticData.FOOD_STATUS_UP);
        //菜品类型
        product1.setProductType(bean.getProductTypeId());
        //更新时间
        product1.setUpdateTime(LocalDateTime.now());
        //几份包装
        product1.setSeveralPackages(bean.getProductPackage());

        productListMapper.insert(product1);
    }

    @Override
    public void modifyPrice(ModifyPriceParam bean) {
        Integer id = TokenTool.getUserIdByToken(bean.getToken());
        QueryWrapper<Shops> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account_id",id);
        Shops shops = shopsMapper.selectOne(queryWrapper);
        if (shops== null){
            throw new RuntimeException("未找到您的店铺信息");
        }
        QueryWrapper<ProductList> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("id",bean.getProductId());
        queryWrapper1.eq("shop_id",shops.getId());
        ProductList productList = productListMapper.selectOne(queryWrapper1);
        if (productList==null){
            throw new RuntimeException("未找到该商品");
        }
        //价格不能小于0
        if (bean.getNewPrice().compareTo(BigDecimal.ZERO)<0){
            throw new RuntimeException("修改后的价格不能小于0");
        }
        productList.setPrice(bean.getNewPrice());
        productList.setUpdateTime(LocalDateTime.now());
        productListMapper.updateById(productList);
    }

    @Override
    public void modifyStatus(ModifyStatusParam bean) {
        Integer id = TokenTool.getUserIdByToken(bean.getToken());
        QueryWrapper<Shops> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account_id",id);
        Shops shops = shopsMapper.selectOne(queryWrapper);
        if (shops== null){
            throw new RuntimeException("未找到您的店铺信息");
        }
        QueryWrapper<ProductList> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("id",bean.getProductId());
        queryWrapper1.eq("shop_id",shops.getId());
        ProductList productList = productListMapper.selectOne(queryWrapper1);
        if (productList==null){
            throw new RuntimeException("未找到该商品");
        }
        if (StaticData.FOOD_STATUS_UP==bean.getProductStatus()){
            productList.setProductStatus(StaticData.FOOD_STATUS_UP);
        }else if (StaticData.FOOD_STATUS_DOWN==bean.getProductStatus()){
            productList.setProductStatus(StaticData.FOOD_STATUS_DOWN);
        }
        productList.setUpdateTime(LocalDateTime.now());
        productListMapper.updateById(productList);
    }

    @Override
    public void modifyDiscount(ModifyDiscountParam bean) {
        Integer id = TokenTool.getUserIdByToken(bean.getToken());
        QueryWrapper<Shops> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account_id",id);
        Shops shops = shopsMapper.selectOne(queryWrapper);
        if (shops== null){
            throw new RuntimeException("未找到您的店铺信息");
        }
        QueryWrapper<ProductList> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("id",bean.getProductId());
        queryWrapper1.eq("shop_id",shops.getId());
        ProductList productList = productListMapper.selectOne(queryWrapper1);
        if (productList==null){
            throw new RuntimeException("未找到该商品");
        }
        //对商品折扣价进行参数校验
        if (bean.getDiscountPrice()!=null){
            BigDecimal discountPrice = bean.getDiscountPrice();
            if (discountPrice.compareTo(BigDecimal.ZERO) <= 0 || discountPrice.compareTo(BigDecimal.ONE) >= 0) {
                throw new RuntimeException("折扣价不能小于等于0或大于等于1");
            }
        }
        productList.setDiscountPrice(bean.getDiscountPrice());
        productList.setUpdateTime(LocalDateTime.now());
        productListMapper.updateById(productList);
    }

    @Override
    public void modifyType(ModifyTypeParam bean) {
        Integer id = TokenTool.getUserIdByToken(bean.getToken());
        QueryWrapper<Shops> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account_id",id);
        Shops shops = shopsMapper.selectOne(queryWrapper);
        if (shops== null){
            throw new RuntimeException("未找到您的店铺信息");
        }
        QueryWrapper<ProductType> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("id",bean.getModifyTypeId());
        ProductType productType = productTypeMapper.selectOne(queryWrapper1);
        if (productType==null){
            throw new RuntimeException("未找到该商品类型");
        }
        productType.setProductTypeName(bean.getModifyTypeName());
        productTypeMapper.updateById(productType);
    }

    @Override
    public ProductList queryProductDetail(SelectProShopInfo form) {

        QueryWrapper<ProductList> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",form.getProductId());
        queryWrapper.eq("shop_id",form.getShopId());
        ProductList productList = productListMapper.selectOne(queryWrapper);
        if(productList==null){
            throw new RuntimeException("该商品不存在");
        }
        if(productList.getProductStatus()==StaticData.FOOD_STATUS_DOWN){
            throw new RuntimeException("该商品已下架");
        }
        return productList;
    }

    @Override
    public List<ProductList> queryProductList(Integer shopId) {
        QueryWrapper<ProductList> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("shop_id",shopId);
        List<ProductList> productLists = productListMapper.selectList(queryWrapper);
        return productLists;
    }

    @Override
    public ProductList queryProductDetailById(Integer productId) {
        QueryWrapper<ProductList> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",productId);
        ProductList productList = productListMapper.selectOne(queryWrapper);
        return productList;
    }

    @Override
    public Integer queryProductDetailByShopId(Integer shopId) {
        QueryWrapper<Shops> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("id",shopId);
        Shops shops = shopsMapper.selectOne(queryWrapper1);
        if(shops==null){
            throw new RuntimeException("该店铺不存在");
        }
        return shops.getShopAccountId();
    }

    @Override
    public List<ProductList> selectProductDetail(String token) {
        Integer id = TokenTool.getUserIdByToken(token);
        QueryWrapper<Shops> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account_id",id);
        Shops shops = shopsMapper.selectOne(queryWrapper);
        if(shops==null){
            throw new RuntimeException("未找到您的店铺信息");
        }
        QueryWrapper<ProductList> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("shop_id",shops.getId());
        List<ProductList> productLists = productListMapper.selectList(queryWrapper1);
        return productLists;
    }

    @Override
    public List<QueryProductAllDto> queryProductDetailByToken(String productName) {
        QueryWrapper<ProductList> queryWrapper = new QueryWrapper<>();
        //查询所有商品
        List<QueryProductAllDto> queryProductAllDto=new ArrayList<>();
        List<ProductList> productLists=null;
        if(productName!=null){
            //拼接模糊查询条件
            queryWrapper.like("product_name",productName);
            productLists=productListMapper.selectList(queryWrapper);
        }else{
            productLists= productListMapper.selectList(queryWrapper);
        }

        if(productLists!=null && productLists.size()>0){
          for(ProductList productList:productLists) {
              if(productList.getProductStatus()!=StaticData.FOOD_STATUS_DOWN){
                  QueryProductAllDto queryProductAllDto1 = new QueryProductAllDto();
                  queryProductAllDto1.setProductId(productList.getId());
                  queryProductAllDto1.setProductName(productList.getProductName());
                  //价钱等于 单价*折扣价
                  if(productList.getDiscountPrice()!=null){
                      queryProductAllDto1.setProductPrice(productList.getPrice().multiply(productList.getDiscountPrice()));
                  }else{
                      queryProductAllDto1.setProductPrice(productList.getPrice());
                  }
                  //商品照片
                  queryProductAllDto1.setProductPhoto(productList.getPicture());
                  //商品描述
                  queryProductAllDto1.setProductDescription(productList.getRemark());
                  //商铺id
                  queryProductAllDto1.setShopId(productList.getShopId());
                  queryProductAllDto.add(queryProductAllDto1);
              }
          }
        }
        return queryProductAllDto;
    }

    @Override
    public String queryProductNameId(Integer productId) {
        QueryWrapper<ProductList> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",productId);
        ProductList productList = productListMapper.selectOne(queryWrapper);
        if(productList!=null){
            return productList.getProductName();
        }
        return "";
    }
}
